from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.template import Context, loader
from polls.models import Poll, Choice
from django.core.urlresolvers import reverse

from django.views import generic
class IndexView( generic.ListView ):
	template_name = 'polls/index.html'
	context_object_name = 'lastest_poll_list'

	def get_queryset(self):
		return Poll.objects.order_by('-pub_date')[:5]

def index(request):
	latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
	template = loader.get_template('polls/index.html')
	context = Context({
		'latest_poll_list': latest_poll_list,
	})
	return HttpResponse( template.render(context) )


class DetailView(generic.DetailView):
	model = Poll
	template_name = 'polls/detail.html'

def detail(request, poll_id):
	try:
		poll = Poll.objects.get( pk = poll_id )
	except Poll.DoesNotExist:
		raise Http404
	return render(request, 'polls/detail.html', {'poll':poll} )

class ResultsView( generic.DetailView ):
	model = Poll
	template_name = 'polls/results.html'

def results(request, poll_id):
	poll = get_object_or_404(Poll, pk = poll_id)
	return render(request, 'polls/results.html', {'poll':poll} )


def vote(request, poll_id):
	p = get_object_or_404( Poll, pk=poll_id )
	try:
		selected_choice = p.choice_set.get( pk=request.POST['choice'] )
	except ( KeyError, Choice.DoesNotExist):
		# redisplay the poll voting form 
		return render( request, 'polls/detail.html', {
			'poll': p,
			'error_message': "you didn't select a choice.",
		})
	else:
		selected_choice.votes += 1
		selected_choice.save()
		#
		return HttpResponseRedirect( reverse('polls:results', args=(p.id,)))
